import React from 'react';

// 布局组件类型
const LAYOUT_TYPES = ['Content', 'Sider', 'Header', 'Footer', 'Splitter'];

// 判断是否为布局组件
function isLayoutElement(element: any) {
  if (!React.isValidElement(element)) return false;
  const type = element.type;
  if (typeof type === 'string') return false;
  if (typeof type === 'function' && type.displayName) {
    return LAYOUT_TYPES.includes(type.displayName);
  }
  if (typeof type === 'function' && type.name) {
    return LAYOUT_TYPES.includes(type.name);
  }
  return false;
}

// 判断 children 是否包含布局组件
function hasLayoutChildren(children: React.ReactNode): boolean {
  let found = false;
  React.Children.forEach(children, child => {
    if (isLayoutElement(child)) {
      found = true;
    }
  });
  return found;
}

// 构造布局数组
function genLayoutArray(children: React.ReactNode) {
  // 保持原有顺序，按出现顺序处理所有布局组件
  const arr: any[] = [];
  React.Children.forEach(children, child => {
    if (!isLayoutElement(child)) return;
    const type = (child as any).type;
    const typeName = type.displayName || type.name;
    if (typeName === 'Sider') {
      arr.push({ type: 'sider', element: child });
    } else if (typeName === 'Splitter') {
      arr.push({ type: 'splitter', element: child });
    } else if (typeName === 'Header' || typeName === 'Content' || typeName === 'Footer') {
      arr.push({ type: typeName.toLowerCase(), element: child });
    }
  });

  // 新的合并逻辑：如果前一个或后一个是sider（也可能在两个sider之间），则和sider同级，否则在main的element数组中
  let result: any[] = [];
  let tempMainArr: any[] = [];
  const isMainType = (type: string) => type === 'header' || type === 'content' || type === 'footer';

  arr.forEach((item, idx) => {
    if (isMainType(item.type) || item.type === 'splitter') {
      // 判断前后是否有sider
      const prev = arr[idx - 1];
      const next = arr[idx + 1];
      const prevIsSider = prev && prev.type === 'sider';
      const nextIsSider = next && next.type === 'sider';

      if (prevIsSider || nextIsSider) {
        // 先把tempMainArr推入result
        if (tempMainArr.length > 0) {
          // 检查mainArr里是否有Content
          const hasContent = tempMainArr.some(i => i.type === 'content');
          if (!hasContent) {
            // 如果有Header或Footer但没有Content，插入一个默认Content
            const defaultContent = {
              type: 'content',
              element: React.createElement('div', {
                style: { flex: 1, minWidth: 0, minHeight: 0, display: 'flex' }
              })
            };
            // 插入到Header后或Footer前
            let insertIdx = tempMainArr.findIndex(i => i.type === 'header');
            if (insertIdx !== -1) {
              tempMainArr.splice(insertIdx + 1, 0, defaultContent);
            } else {
              insertIdx = tempMainArr.findIndex(i => i.type === 'footer');
              if (insertIdx !== -1) {
                tempMainArr.splice(insertIdx, 0, defaultContent);
              } else {
                tempMainArr.push(defaultContent);
              }
            }
          }
          result.push({ type: 'main', element: tempMainArr });
          tempMainArr = [];
        }
        // 当前item直接作为同级元素
        result.push(item);
      } else {
        // 放到main的element数组中
        tempMainArr.push(item);
      }
    } else {
      // 其他类型（如sider）
      if (tempMainArr.length > 0) {
        // 检查mainArr里是否有Content
        const hasContent = tempMainArr.some(i => i.type === 'content');
        if (!hasContent) {
          // 如果有Header或Footer但没有Content，插入一个默认Content
          const defaultContent = {
            type: 'content',
            element: React.createElement('div', {
              style: { flex: 1, minWidth: 0, minHeight: 0, display: 'flex' }
            })
          };
          let insertIdx = tempMainArr.findIndex(i => i.type === 'header');
          if (insertIdx !== -1) {
            tempMainArr.splice(insertIdx + 1, 0, defaultContent);
          } else {
            insertIdx = tempMainArr.findIndex(i => i.type === 'footer');
            if (insertIdx !== -1) {
              tempMainArr.splice(insertIdx, 0, defaultContent);
            } else {
              tempMainArr.push(defaultContent);
            }
          }
        }
        result.push({ type: 'main', element: tempMainArr });
        tempMainArr = [];
      }
      result.push(item);
    }
  });

  if (tempMainArr.length > 0) {
    // 检查mainArr里是否有Content
    const hasContent = tempMainArr.some(i => i.type === 'content');
    if (!hasContent) {
      // 如果有Header或Footer但没有Content，插入一个默认Content
      const defaultContent = {
        type: 'content',
        element: React.createElement('div', {
          style: { flex: 1, minWidth: 0, minHeight: 0, display: 'flex' }
        })
      };
      let insertIdx = tempMainArr.findIndex(i => i.type === 'header');
      if (insertIdx !== -1) {
        tempMainArr.splice(insertIdx + 1, 0, defaultContent);
      } else {
        insertIdx = tempMainArr.findIndex(i => i.type === 'footer');
        if (insertIdx !== -1) {
          tempMainArr.splice(insertIdx, 0, defaultContent);
        } else {
          tempMainArr.push(defaultContent);
        }
      }
    }
    result.push({ type: 'main', element: tempMainArr });
  }
  return result;
}

// 渲染布局数组
function renderLayoutChildren(layoutArr: any[]) {
  // 顶层：左右结构，main：上下结构
  return layoutArr.map((item, idx) => {
    if (item.type === 'sider') {
      return (
        <aside key={'sider-' + idx} style={{ width: 200, background: '#f0f2f5', flexShrink: 0 }}>
          {item.element}
        </aside>
      );
    }
    // splitter 在 layoutArr 里，竖着渲染（左右分割）
    if (item.type === 'splitter') {
      return (
        <div
          key={'splitter-' + idx}
          style={{
            width: 4,
            background: '#e0e0e0',
            flexShrink: 0,
            cursor: 'col-resize',
            minHeight: 0,
            minWidth: 0,
          }}
        />
      );
    }
    if (item.type === 'main') {
      // main 内部是上下结构
      return (
        <section key={'main-' + idx} style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0 }}>
          {item.element.map((sub: any, subIdx: number) => {
            return sub.element;
          })}
        </section>
      );
    }
    return null;
  });
}

// Content 组件
export const Content: React.FC<React.PropsWithChildren> = ({ children }) => {
  const innerStyles = {
    flex: 1,
    width: '100%',
    height: '100%'
  }
  if (!hasLayoutChildren(children)) {
    return <main style={innerStyles}>{children}</main>;
  }
  const layoutArr = genLayoutArray(children);

  console.log('content',layoutArr)

  return (
    <main style={{ ...innerStyles, display: 'flex', flexDirection: 'row' }}>
      {renderLayoutChildren(layoutArr)}
    </main>
  );
};
Content.displayName = 'Content';

// Sider 组件
export const Sider: React.FC<React.PropsWithChildren> = ({ children }) => {
  const innerStyles = {
    width: 200,
    background: '#f5f5f5',
    flexShrink: 0,
    minWidth: 0,
    display: 'flex',
    height: '100%',
    minHeight: 0,
  }
  if (!hasLayoutChildren(children)) {
    return <aside style={innerStyles}>{children}</aside>
  }
  const layoutArr = genLayoutArray(children);
  console.log('sider', layoutArr)
  return (
    <aside style={{ ...innerStyles, display: 'flex', flexDirection: 'row' }}>
      {renderLayoutChildren(layoutArr)}
    </aside>
  );
};
Sider.displayName = 'Sider';

// Header 组件
export function Header({ children }): React.FC<React.PropsWithChildren>{
  const innerStyles = { height: 48, background: '#fafafa', borderBottom: '1px solid #eee', flexShrink: 0 }
  if (!hasLayoutChildren(children)) {
    return <header style={innerStyles}>{children}</header>
  }
  const layoutArr = genLayoutArray(children)
  console.log('header',layoutArr)
  return (
    <header style={{ ...innerStyles, display: 'flex', flexDirection: 'row' }}>
      {renderLayoutChildren(layoutArr)}
    </header>
  );
};
Header.displayName = 'Header';

// Footer 组件
export const Footer: React.FC<React.PropsWithChildren> = ({ children }) => {
  const innerStyles = { height: 48, background: '#fafafa', borderTop: '1px solid #eee', flexShrink: 0 }
  if (!hasLayoutChildren(children)) {
    return <footer style={innerStyles}>{children}</footer>
  }
  const layoutArr = genLayoutArray(children)
  console.log('footer',layoutArr)
  return (
    <footer style={{ ...innerStyles, display: 'flex', flexDirection: 'row' }}>
      {renderLayoutChildren(layoutArr)}
    </footer>
  );
};
Footer.displayName = 'Footer';

// Splitter 组件
export const Splitter: React.FC = ({direction=''}) => {
  // 这里简单区分横向/纵向，实际可根据父容器 flexDirection 判断
  // 默认横向
  return (
    <div style={{ width: 4, background: '#e0e0e0', flexShrink: 0, cursor: 'col-resize' }} />
  );
};
Splitter.displayName = 'Splitter';

